import { BaseMod } from "../../base/BaseMod";
import { connMgr } from "../../com/ConnMgr";
import { CreateRoleMod } from "../createRole/CreateRoleMod";
import { EventId } from "../../com/EventMgr";
import { layerMgr } from "../../com/LayerMgr";
import { loadMgr } from "../../com/LoadMgr";
import { modMgr } from "../../com/ModMgr";
import { MsgId } from "../../cfg/Msg";
import { popupMgr } from "../../com/PopupMgr";
import { Views } from "../../cfg/XlsxDef";

/**
 * 登录模块
 */
export const loginMod = _ as LoginMod;
export class LoginMod extends BaseMod {

    logining: boolean;
    sid: number;
    user: string;

    onInit(): void {
        (loginMod as any) = this;

        //获取到服务器列表
        this.onMsg(MsgId.getSvrList, msg => {
            layerMgr.open(Views.LoginView, [msg]);
        });
        //获取到服务器地址
        this.onMsg(MsgId.getSvrHost, msg => {
            if (!msg.host) {
                this.logining = false;
                popupMgr.showFloatText("加入服务器失败,未知错误");
                return;
            }
            if (msg.sid === this.sid) {
                this.onceEvent(EventId.svrConn, data => {
                    if (data.event) {
                        this.logining = false;
                        popupMgr.showFloatText("连接游戏服务器失败：" + data.event.type);
                        connMgr.disConnSvr();
                        return;
                    }
                    this.sendMsg(MsgId.connect, { sid: this.sid, user: this.user });
                });
                connMgr.connSvr(msg.host);
            }
        });
        //连接游戏服务器结果
        this.onMsg(MsgId.connect, msg => {
            this.logining = false;
            if (msg.code === 2) {
                popupMgr.showFloatText("连接游戏服务器失败：" + msg.msg);
                connMgr.disConnSvr();
                return;
            }
            connMgr.disConnGate();
            if (msg.code === 1) {
                //创角
                modMgr.initMod(new CreateRoleMod());
                layerMgr.open(Views.CreateRoleView);
                return;
            }
            this.tosJoinGame();
        });

        this.sendMsg(MsgId.getSvrList);

        this.onMsg(MsgId.joinGame, msg => {
            if (msg.code) return popupMgr.showFloatText(msg.msg);
            loadMgr.loadGame(msg.data);
        })

        this.onMsg(MsgId.readyEnterMap, () => {
            layerMgr.close(Views.LoadingView);
        })

    }

    tosLogin(sid: number, user: string) {
        if (this.logining) return;
        this.sid = sid;
        this.user = user;
        this.sendMsg(MsgId.getSvrHost, { sid });
    }

    tosJoinGame() {
        this.sendMsg(MsgId.joinGame);
    }

    tosReadyEnterMap() {
        this.sendMsg(MsgId.readyEnterMap);
    }

}